﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace LockCrypt {
    /// <summary>
    /// P/Invoke for getting the last user activity time.
    /// </summary>
    public class InactivityTimer {
        [DllImport("user32.dll")]
        static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

        [StructLayout(LayoutKind.Sequential)]
        struct LASTINPUTINFO {
            public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));
            [MarshalAs(UnmanagedType.U4)]
            public int cbSize;
            [MarshalAs(UnmanagedType.U4)]
            public UInt32 dwTime;
        }

        /// <summary>
        /// Gets the number of seconds elapsed since the user was last active.
        /// </summary>
        /// <returns>The number of seconds elapsed since the last user input.</returns>
        public static int GetLastInputTime() {
            int idleTime = 0;
            LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
            lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
            lastInputInfo.dwTime = 0;

            int envTicks = Environment.TickCount;

            if(GetLastInputInfo(ref lastInputInfo)) {
                int lastInputTick = Convert.ToInt32(lastInputInfo.dwTime);
                idleTime = envTicks - lastInputTick;
            }
            return ((idleTime > 0) ? (idleTime / 1000) : idleTime);
        }
    }
}
